<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2019/6/5 0005
 * Describe: 新颜接收回调类.
 */

namespace app\api\controller\xinyan;

use think\Controller;
use think\Log;
use think\Db;

class Callback extends Controller
{
    public static $xinyanConfig = [];

    public function __construct()
    {
        parent::__construct();

        //日志初始化保存地址
        $setPath = strtolower(request()->module().'/'.request()->controller().'/'.request()->action().'/');
        Log::init(['path' => LOG_PATH.$setPath, 'type' => 'file']);

        self::$xinyanConfig = (new Xinyan())->getXinyanConfig();
    }

    /**
     * 接收运营商原始数据.
     */
    public function addOperator()
    {
        $param = input('');
        $result = false;
        if (isset($param['success']) && $param['success']) {//新颜返回 true||false
            $apiEnc = $this->getApiEnc();
            $url = 'https://qz.xinyan.com/api/user/data?apiUser='.self::$xinyanConfig['apiUser'].'&apiEnc='.$apiEnc.'&token='.$param['token'];
            $result1 = $this->doGet($url);
            $result2 = json_decode($result1, true);
            $calls1 = $this->handleCalls($result2['detail']['data']['calls']);
            $calls = json_encode($calls1, JSON_UNESCAPED_UNICODE); //原始数据中的通话记录
            $mobile = $result2['detail']['data']['carrierUserInfo']['mobile'];
            $userId = model('User')->getIdUserInfo($mobile, 'ID,isMobile');

            // 启动事务
            Db::startTrans();
            try {
                //检测用户是否已有新颜原始数据，有更新 无则添加
                $isOperator = db('moxie_origin')->where(['UserID' => $userId['ID'], 'Type' => 2])->value('ID');
                if ($isOperator) {
                    $temp = [
                        'ID' => $isOperator,
                        'OriginData' => $result1, //原始数据
                        'UpdateTime' => date('Y-m-d H:i:s'),
                        'calls' => $calls, //通话记录
                    ];
                    db('moxie_origin')->update($temp);
                } else {
                    $temp = [
                        'UserID' => $userId['ID'],
                        'OriginData' => $result1, //原始数据
                        'CreateTime' => date('Y-m-d H:i:s'),
                        'calls' => $calls, //通话记录
                        'Type' => 2, //新颜类型数据
                    ];
                    db('moxie_origin')->insert($temp);
                }

                //更新会员表认证状态
                if($userId['isMobile'] != 1){
                    db('mem_info')->where(['ID' => $userId['ID']])->update(['isMobile' => 1,'TrueName2' => $result2['detail']['data']['carrierUserInfo']['name']]);
                }

                //检测手机认证表是否有数据，有更新 无则添加
                $isModel = db('renzen_mobile')->where(['UserID' => $userId['ID'], 'Type' => 2])->value('ID');
                if($isModel){
                    $temp = [
                        'ID' => $isOperator,
                        'ZUserName' => $result2['detail']['data']['carrierUserInfo']['name'], //用户姓名
                        'Status' => 1,//认证状态 成功
                        'UpdateTime' => date('Y-m-d H:i:s'),
                        'mobile' => $result2['detail']['data']['carrierUserInfo']['mobile'], //用户手机号
                    ];
                    db('renzen_mobile')->update($temp);
                }else{
                    $temp = [
                        'ID' => $isOperator,
                        'UserID' => $userId['ID'],
                        'ZUserName' => $result2['detail']['data']['carrierUserInfo']['name'], //用户姓名
                        'Status' => 1,//认证状态 成功
                        'RenzTime' => date('Y-m-d H:i:s'),
                        'mobile' => $result2['detail']['data']['carrierUserInfo']['mobile'], //用户手机号
                        'Type' => 2, //新颜类型数据
                    ];
                    db('renzen_mobile')->insert($temp);
                }

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();

                //写入错误日志
                \Think\Log::record('接收新颜回调原始数据错误记录1 '.$e->getMessage());
                die;
            }

            //检测成功 返回给新颜200状态码
            echo 200;
            die;
        } else {
            \Think\Log::record('接收新颜回调原始数据错误记录2 '.json_encode($param));
        }
    }

    /**
     * 接收运营商报告数据.
     */
    public function addOperatorReport()
    {
        $param = input('');
        $result = false;
        if ($param['success']) {
            $apiEnc = $this->getApiEnc();
            $url = 'https://qz.xinyan.com/api/user/data/report/json?apiUser='.self::$xinyanConfig['apiUser'].'&apiEnc='.$apiEnc.'&token='.$param['token'];
            $result1 = $this->doGet($url);
            $result2 = json_decode($result1, true);
            $calls1 = $this->handleRanking($result2['detail']['friend_circle']['call_num_top10_6m']);
            $TongoHuaPaiHang = json_encode($calls1, JSON_UNESCAPED_UNICODE); //通话排行数据
            $mobile = $result2['detail']['user_basic_info']['mobile'];
            $userId = model('User')->getIdUserInfo($mobile, 'ID');

            //检测用户是否已有新颜报告数据，有更新 无则添加
            $isReport = db('moxie_report')->where(['UserID' => $userId['ID'], 'Type' => 2])->value('ID');
            if ($isReport) {
                $temp = [
                    'ID' => $isReport,
                    'ReportData' => $result1, //原始数据
                    'UpdateTime' => date('Y-m-d H:i:s'),
                    'TongoHuaPaiHang' => $TongoHuaPaiHang, //通话排行
                ];
                $result = db('moxie_report')->update($temp);
            } else {
                $temp = [
                    'UserID' => $userId['ID'],
                    'ReportData' => $result1, //原始数据
                    'CreateTime' => date('Y-m-d H:i:s'),
                    'TongoHuaPaiHang' => $TongoHuaPaiHang, //通话排行
                    'Type' => 2, //新颜类型数据
                ];
                $result = db('moxie_report')->insert($temp);
            }
        } else {
            \Think\Log::record('接收新颜回调报告数据错误记录 '.json_encode($param));
        }

        //检测成功 返回给新颜200状态码
        if ($result) {
            echo 200;
            die;
        }
    }

    /**
     * 处理通话记录数据
     * @param array $callData 通话记录数据
     * @return array
     */
    public function handleCalls($callData)
    {
        if(empty($callData)){
            return [];
        }

        foreach ($callData as $k=>$v){
            $callData[$k]['peer_number'] = $v['peerNumber']??'';
            $callData[$k]['dial_type'] = $v['dialType']??'';
            $callData[$k]['location_type'] = $v['locationType']??'';
        }

        return $callData;
    }

    /**
     * 处理通话排行
     * @param array $rankingData 通话排行数据
     * @return array
     */
    public function handleRanking($rankingData)
    {
        if(empty($rankingData)){
            return [];
        }

        foreach ($rankingData as $k=>$v){
            $rankingData[$k]['city'] = $v['city']??'';//通话城市
            $rankingData[$k]['name'] = $v['company_name']??'';//通话人姓名
            $rankingData[$k]['peer_num'] = $v['peer_number']??'';//电话号码
            $rankingData[$k]['call_cnt_6m'] = $v['call_num']??'';//次数
        }

        return $rankingData;
    }

    /**
     * 获取延签.
     */
    public function getApiEnc()
    {
        return md5(self::$xinyanConfig['apiUser'].self::$xinyanConfig['apiKey']);
    }

    /**
     * @param string $url
     *
     * @return mixed
     */
    public function doGet($url)
    {
        //初始化
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        // 执行后不直接打印出来
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 不从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);

        return $output;
    }
}
